package com.tree.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tree.backend.common.Result;
import com.tree.backend.entity.dto.UserDTO;
import com.tree.backend.entity.pojo.User;
import com.tree.backend.entity.vo.UserVO;
import com.tree.backend.mapper.UserMapper;
import com.tree.backend.service.IUserService;
import com.tree.backend.utils.DataMappingUtils;
import com.tree.backend.utils.JwtUtil;
import com.tree.backend.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


@Slf4j

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final JwtUtil jwtUtil;

    @Override
    public Result<UserVO> login(UserDTO userDTO) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 账号和密码不能为空，不能为null
        if (StringUtils.isBlank(userDTO.getUsername()) || StringUtils.isBlank(userDTO.getPassword()))
            return Result.error("账号或密码不能为空");

        lambdaQueryWrapper.eq(User::getUsername, userDTO.getUsername());
        User user = this.getOne(lambdaQueryWrapper);
        if (user == null) return Result.error("账号不存在");

        if (!user.getPassword().equals(userDTO.getPassword())) return Result.error("密码错误");

        // 生成token，包含用户ID和公司ID
        String token = jwtUtil.generateToken(user.getId(), user.getCompanyId());
        UserVO userVO = UserVO.builder().token(token).build();
        return Result.success(userVO);
    }

    @Override
    public Result<Page<UserVO>> getList(UserDTO userDTO) {
        Page<User> userPage = new Page<>(userDTO.getPage(), userDTO.getPageSize());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(UserContext.getCompanyId() != 0, User::getCompanyId, UserContext.getCompanyId())
                .like(StringUtils.isNotBlank(userDTO.getUsername()), User::getUsername, userDTO.getUsername())
                .like(StringUtils.isNotBlank(userDTO.getRealName()), User::getRealName, userDTO.getRealName())
                .like(StringUtils.isNotBlank(userDTO.getPhone()), User::getPhone, userDTO.getPhone())
                .eq(userDTO.getStatus() != null, User::getStatus, userDTO.getStatus());

        Page<User> page = page(userPage, lambdaQueryWrapper);
        // 使用通用工具类将Page<User>转换为Page<UserVO>
        Page<UserVO> userVOPage = DataMappingUtils.convertPage(page, UserVO.class);
        return Result.success(userVOPage);
    }
    
    @Override
    public Result<UserVO> getCurrentUser() {
        // 从UserContext获取当前登录用户的ID
        Long userId = Long.valueOf(UserContext.getUserId());
        if (userId == -1) {
            return Result.error("用户未登录");
        }
        
        // 根据ID查询用户信息
        User user = this.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 将User转换为UserVO
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return Result.success(userVO);
    }
}
